<?php

namespace app\system\controller;

use app\common\controller\System;
use app\system\controller\daily\Throwable;
use hehe\Str;
use hehe\Trade;
use think\facade\Db;
use think\facade\Lang;


class Customer extends System {
    /**
     * Goods模型对象
     * @var object
     */
    protected object $model;

    protected string|array $defaultSortField = 'id,desc';

    protected array|string $preExcludeFields = ['id', 'create_time'];

    protected string|array $quickSearchField = ['corp_name_cn', 'corp_name_ko', 'manager'];

    public function initialize(): void {
        parent::initialize();
        $this->model = new \app\system\model\Customer;
    }




    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void {
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->param('select')) {
            $this->select();
        }
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)->where(['filter_id' => $this->filter['id']]);
        $param = $this->request->param();

        if(!empty($param['type'])){
            $res = $res->where('FIND_IN_SET(:value,type)',['value' => $param['type']]);
        }
        $res = $res->order($order)->paginate($limit);

        $lang = Lang::getLangSet();

        $list = $res->items();
        foreach($list as $key => $val){
            if($lang == 'zh-cn'){
                $list[$key]['corp_name'] = $val['corp_name_cn'];
            }else{
                $list[$key]['corp_name'] = $val['corp_name_' . $lang];
            }
            $list[$key]['type'] = explode(',', $val['type']);
        }


        $this->success('', [
            'list' => $list,
            'total' => $res->total(),
            'remark' => get_route_remark(),
        ]);
    }

    public function add(): void {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data = $this->excludeFields($data);
            if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                $data[$this->dataLimitField] = $this->auth->id;
            }

            $data['type'] = empty($data['type']) ? null : implode(',', $data['type']);
            $data['filter_id'] = $this->filter['id'];
            $result = false;
            $this->model->startTrans();
            try {
                // 模型验证
                if ($this->modelValidate) {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    if (class_exists($validate)) {
                        $validate = new $validate;
                        if ($this->modelSceneValidate) $validate->scene('add');
                        $validate->check($data);
                    }
                }
                $result = $this->model->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }



    public function edit(): void
    {
        $id  = $this->request->param($this->model->getPk());
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds && !in_array($row[$this->dataLimitField], $dataLimitAdminIds)) {
            $this->error(__('You have no permission'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }

            $data   = $this->excludeFields($data);
            $data['type'] = empty($data['type']) ? null : implode(',', $data['type']);
//            print_r($data);die;
            $result = false;
            $this->model->startTrans();
            try {
                $result = $row->save($data);
                $this->model->commit();
            } catch (Throwable $e) {
                $this->model->rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Update successful'));
            } else {
                $this->error(__('No rows updated'));
            }
        }
        $row = $row->toArray();


        $row['type'] = empty($row['type']) ? [] : explode(',', $row['type']);

        $this->success('', [
            'row' => $row
        ]);
    }



    /**
     * 删除报价单
     */
    public function delQuotationFile(): void {
        $id = $this->request->param('id');
        $update = [
            'quotation_file' => null,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $id])->update($update);
        $this->success();
    }

    /**
     * 上传报价单
     */
    public function setQuotationFile(): void{
        $param = $this->request->post();
//        print_r($param);
        $quotation_file = json_encode($param['quotation_file']);
        $update = [
            'quotation_file' => $quotation_file,
            'update_time' => $this->timestamp
        ];
        db::name('business_quotation')->where(['id' => $param['id']])->update($update);
        $this->success();
    }


    /**
     * 删除备注
     */
    public function delNote(){
        $param = $this->request->param();
        db::name('business_quotation_note')->where(['id' => $param['id']])->delete();
        $this->success();
    }

    /**
     * 添加备注
     */
    public function addNote(){
        $param = $this->request->param();
        $param['admin_id'] = $this->auth->id;
        $param['create_time'] = $this->timestamp;
        $note_id = db::name('business_quotation_note')->insertGetId($param);
        if($note_id){
            $this->success('', [
                'id' => $note_id,
                'content' => $param['content'],
                'admin' => [
                    'username' => $this->auth->username
                ]

            ]);
        }else{
            $this->error();
        }
    }

    /**
     * 隐藏报价
     */
    public function hideQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 1]);
        $this->success();
    }
    /**
     * 显示报价
     */
    public function showQuotation(){
        $param = $this->request->param();
        db::name('business_quotation')->where(['id' => $param['id']])->update(['hide' => 0]);
        $this->success();
    }


































}